// pages/myself/coupon/UseCoupon.js
var Zan = require('../../../dist/index.js');
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.min.js');
let WxNotificationCenter = require('../../../utils/WxNotificationCenter.js');
let network = null;
let utils = null;
let api = null;
const app = getApp();
let constants = null;
Page(Object.assign({}, Zan.TopTips, Zan.Toast, {

  /**
   * 页面的初始数据
   */
  data: {
    couponId: '',
    couponInfo:{},
    stores:[],
    useCoupon:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();
    // 注册列表刷新事件
    WxNotificationCenter.addNotification("RefreshNotification", this.refreshNotification, this)
    this.setData({
      couponId: options.couponId
    })

    constants = new app.Constants();
    var that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        let latitude = res.latitude
        let longitude = res.longitude
        wx.request({
          url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${constants.key}`,
          success: res => {
            console.log(res);
            let location = res.data.result.ad_info;
            that.setData({
              lng: res.data.result.location.lng,
              lat: res.data.result.location.lat,
              province: location.province,
              city: location.city,
              district: location.district
              // region: [location.province, location.city, location.district]
            })
            that.onPullDownRefresh()
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    WxNotificationCenter.removeNotification("RefreshNotification", this)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    this.setData({
      stores:[]
    })
    network._post_json(this, api.couponDetails, { couponId: this.data.couponId, lat: this.data.lat, lng: this.data.lng }, success);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  goMap: function (e) {
    //114.35663,30.52636
    var lat = e.currentTarget.dataset.lat;
    var lng = e.currentTarget.dataset.lng;
    wx.openLocation({
      type: 'wgs84 ',
      latitude: lat,
      longitude: lng,
      scale: 18
    });
  },
  scanCoupon: function () {
    wx.scanCode({
      success: (res) => {
        console.log(res);
        if (res.path){
          let scene = decodeURIComponent(res.path);
          let index = scene.indexOf('scene='); 
          if (index == -1) {
            this.showZanTopTips(this.error, '无效门店二维码！');
          }else{
            let storeId = scene.substring(index + 6, scene.length);
            console.log(scene.substring(index + 6, scene.length));
            network._post_json(this, api.userCoupon, { couponId: this.data.couponId, storeId: storeId }, userSuccess);
          }
          
        } else if (res.result == "" ) {
          this.showZanTopTips(this.error, '无效门店二维码！');
        } else if (res.result == "*") {
          this.showZanTopTips(this.error, '无效门店二维码！');
        } else{
          this.showZanTopTips(this.error, '无效门店二维码！');
        }
      }
    })
  },
  refreshNotification:function(){
    this.setData({
      stores: []
    })
    network._post_json(this, api.couponDetails, { couponId: this.data.couponId, lat: this.data.lat, lng: this.data.lng }, success);
  }
}))
var success = function(that,res){
  res.data.data.startTime = utils.formatDate02(new Date(res.data.data.startTime))
  res.data.data.endTime = utils.formatDate02(new Date(res.data.data.endTime))
  for (let j = 0; j < res.data.data.stores.length; j++) {
    res.data.data.stores[j].openTime = utils.formatDate03(new Date(res.data.data.stores[j].openTime))
    res.data.data.stores[j].closeTime = utils.formatDate03(new Date(res.data.data.stores[j].closeTime))
  }
  if(res.data.data){
    that.setData({
      couponInfo:res.data.data,
      stores: that.data.stores.concat(res.data.data.stores)
    })
  }
}
var userSuccess = function(that,res){
  WxNotificationCenter.postNotificationName("RefreshNotification");
  console.log(res.data);
  if (res.data){
    WxNotificationCenter.postNotificationName("RefreshMyCoupon");
    that.showZanToast('使用成功！');
    that.setData({
      useCoupon:1
    })

  }
}